package com.tz.tzgw.pc.web.dao;

import com.tz.tzgw.pc.web.model.Article;
import com.tz.tzgw.pc.web.model.PageResult;
import com.tz.tzgw.pc.web.model.ZtArticle;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class ZtArticleDao {
    private final JdbcTemplate jdbcTemplate;

    public ZtArticleDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    public PageResult<ZtArticle> getZtArticlesByPageAndCondition(int pageNum, int pageSize,Long setid) {
        PageResult<ZtArticle> pageResult = new PageResult<>();
        int offset = (pageNum - 1) * pageSize;

        // 构建查询总条数的 SQL
        StringBuilder countSqlBuilder = new StringBuilder("SELECT COUNT(*) FROM tz_zt_article");
        List<Object> countParams = new ArrayList<>();

        // 构建分页查询的 SQL
        StringBuilder querySqlBuilder = new StringBuilder("SELECT id, setid,title, thumb, hit, istop, istui,status,create_at FROM tz_zt_article ");
        List<Object> queryParams = new ArrayList<>();

        if (setid != null) {
            countSqlBuilder.append(" WHERE setid = ?");
            countParams.add(setid);

            querySqlBuilder.append(" WHERE setid = ?");
            queryParams.add(setid);
        }

        // 查询总条数
        String countSql = countSqlBuilder.toString();
        int total = jdbcTemplate.queryForObject(countSql, Integer.class, countParams.toArray());
        pageResult.setTotal(total);

        // 分页查询
        querySqlBuilder.append(" ORDER BY sort_order DESC LIMIT ?, ?");
        queryParams.add(offset);
        queryParams.add(pageSize);

        String querySql = querySqlBuilder.toString();
        List<ZtArticle> articles = jdbcTemplate.query(querySql, new BeanPropertyRowMapper<>(ZtArticle.class), queryParams.toArray());
        pageResult.setData(articles);

        return pageResult;
    }


    public int insertOrUpdateZtArticle(ZtArticle ztarticle) {
        Long id = ztarticle.getId();
        if (id != null) {
            // Update
            String sql = "UPDATE tz_zt_article SET ";
            List<String> updateFields = new ArrayList<>();
            List<Object> params = new ArrayList<>();

            if (ztarticle.getTitle() != null) {
                updateFields.add("title = ?");
                params.add(ztarticle.getTitle());
            }
            if (ztarticle.getSetid() != null) {
                updateFields.add("setid = ?");
                params.add(ztarticle.getSetid());
            }
            if (ztarticle.getThumb() != null) {
                updateFields.add("thumb = ?");
                params.add(ztarticle.getThumb());
            }
            if (ztarticle.getContent() != null) {
                updateFields.add("content = ?");
                params.add(ztarticle.getContent());
            }
            if (ztarticle.getHit() != null) {
                updateFields.add("hit = ?");
                params.add(ztarticle.getHit());
            }
            if (ztarticle.getIstop() != null) {
                updateFields.add("istop = ?");
                params.add(ztarticle.getIstop());
            }
            if (ztarticle.getIstui() != null) {
                updateFields.add("istui = ?");
                params.add(ztarticle.getIstui());
            }
            if (ztarticle.getStatus() != null) {
                updateFields.add("status = ?");
                params.add(ztarticle.getStatus());
            }

            if (ztarticle.getSort_order() != null) {
                updateFields.add("sort_order = ?");
                params.add(ztarticle.getSort_order());
            }

            if (ztarticle.getCreate_at() != null) {
                updateFields.add("create_at = ?");
                params.add(ztarticle.getCreate_at());
            }

            sql += String.join(", ", updateFields);
            sql += " WHERE id = ?";

            // 添加 id 参数
            params.add(id);

            jdbcTemplate.update(sql, params.toArray());
        } else {
            // Insert
            String sql = "INSERT INTO tz_zt_article (title, setid, thumb, content, hit, istop, istui,status,sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            String customCreateAt = null;
            if (ztarticle.getCreate_at() != null) {
                customCreateAt = ztarticle.getCreate_at();
            }

            Object[] params = new Object[9];

            if (customCreateAt != null) {
                params = new Object[10];
                sql = "INSERT INTO tz_zt_article (title, setid, thumb, content, hit, istop, istui,status,sort_order,create_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                params[9] = customCreateAt;
            }
            params[0] = ztarticle.getTitle();
            params[1] = ztarticle.getSetid();
            params[2] = ztarticle.getThumb();
            params[3] = ztarticle.getContent();
            params[4] = ztarticle.getHit();
            params[5] = ztarticle.getIstop();
            params[6] = ztarticle.getIstui();
            params[7] = ztarticle.getStatus();
            params[8] = ztarticle.getSort_order();

            jdbcTemplate.update(sql, params);
        }
        return 1;
    }

    public ZtArticle getArticleById(Long id) {
        String sql = "SELECT * FROM tz_zt_article WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(ZtArticle.class));
    }


    public Integer deleteArticle(Integer id) {
        String sql = "DELETE FROM tz_zt_article WHERE id = ?";
        jdbcTemplate.update(sql, id);
        return 1;
    }

    public ZtArticle getPrevArticleById(Long articleId) {
        String sql = "SELECT * FROM tz_zt_article WHERE id < ? ORDER BY id DESC LIMIT 1";
        List<ZtArticle> articles = jdbcTemplate.query(sql, new Object[]{articleId}, new BeanPropertyRowMapper<>(ZtArticle.class));
        if (articles.isEmpty()) {
            return null;
        }
        return articles.get(0);
    }

    public ZtArticle getNextArticleById(Long articleId) {
        String sql = "SELECT * FROM tz_zt_article WHERE id > ? ORDER BY id ASC LIMIT 1";
        List<ZtArticle> articles = jdbcTemplate.query(sql, new Object[]{articleId}, new BeanPropertyRowMapper<>(ZtArticle.class));
        if (articles.isEmpty()) {
            return null;
        }
        return articles.get(0);
    }

    public void incrementField(Long id, String fieldName) {
        String sql = "UPDATE tz_zt_article SET " + fieldName + " = " + fieldName + " + 1 WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }
}
